package com.xjiuge.ctrl;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xjiuge.bean.Role;
import com.xjiuge.bean.User;
import com.xjiuge.service.RoleService;
import com.xjiuge.service.UserService;
import com.xjiuge.util.JsonResult;
import com.xjiuge.util.Md5Util;

@Controller
public class Reg_Ctrl {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	
	@RequestMapping("reg")
	@ResponseBody
	public JsonResult reg(String username,String password,String role_id,String email){
		User user = new User();
		user.setUserName(username);
		user.setPassword(Md5Util.getMd5(password));
		user.setEmail(email);
		if(role_id!=null){
			user.setRoleId(Integer.valueOf(role_id));
		}
		
		List<User> listUser = userService.findByPorperty("userName",username,"password",password,"email",email);
		if(listUser!=null && listUser.size()>0){
			return new JsonResult(500, "该用户名已存在");
		}
		userService.save(user);
		return JsonResult.success();
	}
	
	@RequestMapping("login")
	@ResponseBody
	public JsonResult login(String username,String password,HttpSession httpSession,String code){
		List<User> listUser = userService.findByPorperty("userName",username,"password",Md5Util.getMd5(password));
		List<User> listUserAll = userService.findByPorperty();
		List<Role> listRole = roleService.findByPorperty();
		if(listUser==null || listUser.size()<=0){
			return new JsonResult(500, "用户名或密码不正确");
		}
		
		String randomCode = (String) httpSession.getAttribute("randomCode");
		if(!code.equals(randomCode)){
			return new JsonResult(500, "验证码不正确");
		}
		httpSession.setAttribute("user", listUser.get(0));
		httpSession.setAttribute("listUser", listUserAll);
		httpSession.setAttribute("listRole", listRole);
		return JsonResult.success();
	
	}
	@RequestMapping("admin/login")
	public String admin_login(String username,String password,HttpSession httpSession){
		List<User> listUser = userService.findByPorperty("userName",username,"password",Md5Util.getMd5(password));
		List<User> listUserAll = userService.findByPorperty();
		List<Role> listRole = roleService.findByPorperty();
		if(listUser==null || listUser.size()<=0){
			return null;
		}
		httpSession.setAttribute("user", listUser.get(0));
		httpSession.setAttribute("listUser", listUserAll);
		httpSession.setAttribute("listRole", listRole);
		return "index";
		
	}
}
